package m202406.d09;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/9 11:49
 */
public class Q15 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int first = 0; first < nums.length; first++) {
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            if (nums[first] > 0) {
                return res;
            }
            int target = -nums[first];
            for (int second = first + 1, third = nums.length - 1; second < third; ) {
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    second++;
                    continue;
                }
                int temp = nums[second] + nums[third];
                if (temp < target) {
                    second++;
                } else if (temp > target) {
                    third--;
                } else {
                    res.add(List.of(nums[first], nums[second], nums[third]));
                    second++;
                }
            }
        }
        return res;
    }
}
